<template>


  <div class="body">
   <view class="card">
     <view class="desc">
       对声音进行高质量的分离，提取出背景音乐和人声2个音轨。常用于声音分离、去人声、人声消除、bgm提取、人声提取、伴奏提取、卡拉OK伴奏制作。
     </view>

     <button class="mainbg" :disabled="disabled" :loading="loading" @click="selectVideo">{{ btntext }}</button>
   </view>
    <div class="voice" v-if="currentFile.vocals">
      <view v-if="currentFile.vocals">
        <view>人声：</view>
        <audio style="text-align: left"  :src="currentFile.vocals"  controls></audio>
        <button @click="downloadVoice(currentFile.vocals)">下载</button>
      </view>
      <view v-if="currentFile.accompaniment">
        <view>背景声：</view>
        <audio style="text-align: left"  :src="currentFile.accompaniment"  controls></audio>
        <button @click="downloadVoice(currentFile.accompaniment)">下载</button>
      </view>
    </div>


    <div class="dialog" v-if="showDialog">

      <div class="content">
        <textarea v-model="linkValue" class="textarea" placeholder="请输入复制的链接 或 点击粘贴链接按钮"/>
        <view class="linkopt" >
          <button class="smallBtn bg2" @click="paste">粘贴链接</button>
          <button class="smallBtn bg1" @click="start">解析链接</button>

        </view>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref,onUnmounted} from 'vue'
import {str_md5} from "../../utils/md5";
import vaudio from '@/components/h-custom-audio/index.vue'
let btntext = ref('选择音频、视频')
let platform=ref('')
import parsePlatform from "../../utils/platform";
import request from "../../utils/request";
let linkValue = ref('')
let videoUrl = ref([])
let disabled=ref(false)
let loading=ref(false)
let currentFile = ref({})
let intervalId= ref(0)
let globalData = getApp().globalData;

let showDialog=ref(false)
function downloadVoice(link){
  let url1 = link


  uni.showLoading({
    title: '加载中'
  });
  console.log(url1, 'ster');
  let downloadTask = uni.downloadFile({
    url: url1,
    header: {
      Accept: "*/*",
      referer: url1

    },
    success: (res) => {

      if (res.statusCode === 200) {
        const tempFilePath = res.tempFilePath;
        // 保存图片到相册
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.writePhotosAlbum']) {
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  uni.saveVideoToPhotosAlbum({
                    filePath: tempFilePath,
                    success: () => {
                      uni.showToast({
                        title: '保存视频成功',
                        duration: 2000
                      });

                    },
                    fail: (error) => {
                      uni.showToast({
                        icon: 'error',
                        title: '保存视频失败',
                        duration: 2000
                      });
                      console.log('保存视频失败', error);
                    }
                  });
                }
              })
            } else {
              uni.saveVideoToPhotosAlbum({
                filePath: tempFilePath,
                success: () => {
                  uni.showToast({
                    title: '保存视频成功',
                    duration: 2000
                  });

                },
                fail: (error) => {
                  uni.showToast({
                    icon: 'error',
                    title: '保存视频失败',
                    duration: 2000
                  });
                  console.log('保存视频失败', error);
                }
              });

            }
          }
        })


      } else {
        uni.showToast({
          title: '下载视频失败',
          duration: 2000
        });
        console.log('下载视频失败');
      }
    },
    fail: (error) => {
      if(error.errMsg==='downloadFile:fail exceed max file size'){
        uni.showModal({
          content: '小程序不支持下载超过200M的文件，请复制视频链接到浏览器中下载',
          showCancel:false

        });
      }
      if(error.errMsg==='downloadFile:fail createDownloadTask:fail url not in domain list'){
        uni.showModal({
          content: '小程序不支持此下载域名，请复制视频链接到浏览器中下载',
          showCancel:false

        });
      }

      console.log('下载视频失败', error);
    },
    complete: () => {
      uni.hideLoading();
    }
  });
  downloadTask.onProgressUpdate((res) => {
    console.log('下载进度' + res.progress);
    // console.log('已经下载的数据长度' + res.totalBytesWritten);
    // console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);

    // 满足测试条件，取消下载任务。
    uni.showToast({
      icon: 'loading',
      title: '下载进度：' + res.progress + '%',

    });
  });

}

function uploadVideo(index) {

  if(index===0){
    return new Promise((resolve,reject)=>{
      uni.chooseVideo({
        sourceType: ['album'],
        compressed: false,
        success: function (res) {
          let tempinfo = res.tempFilePath;
          resolve(tempinfo)


        }
      });
    })
  }
  if(index===1){
    return new Promise((resolve,reject)=>{

      wx.chooseMessageFile({
        count: 1,
        type: 'video',
        success (res) {
          // tempFilePath可以作为img标签的src属性显示图片

          const tempFilePaths = res.tempFiles
          console.log(tempFilePaths);
          resolve(tempFilePaths[0].path)
        }
      })
    })
  }
  if(index===2){
    showDialog.value=  true;

  }


}
function chuli(tempinfo){
  let uploadTask = uni.uploadFile({
    url: globalData.url+'/humanvoice', //仅为示例，非真实的接口地址
    filePath: tempinfo,
    name: 'file',
    timeout: 10000000,
    formData: {
      'tempinfo': tempinfo,
      'encrypt': str_md5(tempinfo + 'humanvoice')
    },
    success: (uploadFileRes) => {
      if(uploadFileRes.data==='解析错误'){

      }else{
        let data = JSON.parse(uploadFileRes.data)
        console.log(data);
        if (data.code === 200) {
          let d = data.data;


          let dingshi = setInterval(()=>{
            uni.request({
              url:d.vocals
            }).then(res=>{
              if(res.data!=='Hello World hhh'){
                clearInterval(dingshi)
                btntext.value = '人声分离成功'
                currentFile.value  = d

              }else{
                btntext.value = '人声分离中...'
              }

            })
          },1000)

        }
      }


    }
  });
  uploadTask.onProgressUpdate((p) => {

    btntext.value = '上传进度' + p.progress + '%'
    if (p.progress === 100) {
      btntext.value = '上传完成'
    }
  })
}

function upload(index){
  uploadVideo(index).then(tempinfo=>{
    chuli(tempinfo)
  })

}

function selectVideo(){
  uni.showActionSheet({
    itemList: ['手机相册', '微信文件', '短视频链接'],
    success: function (res) {
      upload(res.tapIndex)

    },
    fail: function (res) {
      console.log(res.errMsg);
    }
  });
}
function paste() {
  uni.getClipboardData({
    success: function (res) {
      console.log(res.data);
      linkValue.value = res.data
    }
  });
}
//开始解析
async function start() {

  platform.value = parsePlatform(linkValue.value)
  if(platform.value==='bilibili'){
    let bilibili = new Promise(resolve1 => {
      uni.showModal({
        content:"b站解析视频可能很慢，请耐心等待",
        showCancel:false,
        success(res) {
          resolve1()
        }
      })
    })

    await bilibili;


  }
  if(!linkValue.value){
    uni.showModal({
      title: '提示',
      content: '链接不能为空',
      showCancel:false,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定');
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });

    return;
  }
  console.log(3323)
  disabled.value=true;
  loading.value=true;
  request(globalData.url+'/start', {
    link: linkValue.value,
    encrypt:str_md5(linkValue.value+'shuiyin')
  }, {}, 'post').then(res => {
    console.log(res);
    if(res.code===200){


      if (['douyin', 'haokan','huya','xhs', 'xigua', 'kuaishou','zhihu','pipix','kg','weibo','acfun','zuiyou','weishi','toutiao','bilibili'].includes(platform.value)) {

        videoUrl.value = res.data.video;

      }


      console.log(videoUrl.value[0],'22');


      if(videoUrl.value[0]===undefined){

        uni.showModal({
          title: '解析失败3！',
          showCancel:false

        });

      }else{

        request(globalData.url+'/humanvoice', {
          'tempinfo': videoUrl.value[0],
          'encrypt': str_md5(videoUrl.value[0] + 'humanvoice')
        }, {}, 'post').then(uploadFileRes=>{
          console.log(uploadFileRes,'uploadFileRes');

          let data = uploadFileRes.data
          console.log(data,'data',typeof data);

          intervalId.value = setInterval(()=>{
            uni.request({
              url:data.vocals
            }).then(res=>{
              if(res.data!=='Hello World hhh'){
                clearInterval(intervalId.value)
                btntext.value = '人声分离成功'
                console.log(data,'data');
                currentFile.value  = data;

              }else{
                btntext.value = '人声分离中...'
              }

            })
          },1000)
        })


      }

    }else{

      uni.showModal({
        title: '解析失败1！',
        showCancel:false,


      });

    }


  }).catch((e) => {
    console.log(e,'err');

    uni.showModal({
      title: '解析失败2！',
      showCancel:false

    });

  }).finally(()=>{
    disabled.value=false;
    loading.value=false;
    showDialog.value =false;
  })
}
onUnmounted(()=>{
  console.log(33)
  if(intervalId.value){
    clearInterval(intervalId.value)
  }
})
</script>


<style scoped lang="less">
@main-color: #17DC73;
.body{
  position: relative;
  background: #f0f0f0;
  overflow: auto;
  height:100vh;
  .card{
    width: 700rpx;
    margin:0 auto;
    border-radius: 10rpx;
    margin-top: 15rpx;
    background: #fff;
    padding: 15rpx;
    box-sizing: border-box;
    .desc{
      font-size: 25rpx;
    }
  }
  .voice{
    width: 700rpx;
    margin:0 auto;
    border-radius: 10rpx;
    margin-top: 15rpx;
    background: #fff;
    padding: 15rpx;
    box-sizing: border-box;
     }
  .dialog{
    position: absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    width: 750rpx;
    height:100vh;
    background: rgba(0,0,0,0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    .content{
      background: #fff;
      width: 600rpx;
      height:500rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      .textarea{
        width: 500rpx;
        height:300rpx;
        border:1px solid #f0f0f0;
        margin-top: 15rpx;
      }
      .smallBtn {
        width: 225rpx;
        background-color: @main-color;
        font-size: 25rpx;
        color: #fff;
        margin:0;
      }

      .linkopt {
        margin: 10px 0;
        width: 500rpx;
        display: flex;
        justify-content: space-between;


      }



      .bg1 {
        background-color: #1783dc;
      }

      .bg2 {
        background-color: #1783dcaa;
      }

    }

  }
}
.mainbg {
  background-color: @main-color;
  margin-top: 20rpx;
}

</style>